package com.magina.jta.config;

import com.magina.jta.Util.PropUtil;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@EnableConfigurationProperties
@EnableAutoConfiguration
@MapperScan(basePackages = "com.magina.jta.mapper.one", sqlSessionTemplateRef = "jtaMasterSqlSessionTemplateMagina")
public class MasterDataSourceConfig {

//    @Bean
//    @ConfigurationProperties(prefix = "spring.jta.atomikos.datasource.jta-one")
//    @Primary
//    public DataSource dataSourceJTAUser() {
//        return new AtomikosDataSourceBean();
//    }

    @Bean(name = "masterDataSourceMagina")
    @Primary
    @Autowired
    public DataSource masterDataSourceMagina(Environment env) {
        org.springframework.boot.jta.atomikos.AtomikosDataSourceBean ds = new AtomikosDataSourceBean();
        Properties prop = PropUtil.build(env, "spring.datasource.druid.master-db.");
        ds.setXaDataSourceClassName("com.alibaba.druid.pool.xa.DruidXADataSource");
        ds.setUniqueResourceName("master-db");
        ds.setPoolSize(5);
        ds.setXaProperties(prop);
        return ds;
    }
    @Bean
    @Primary
    public SqlSessionFactory jtaMasterSqlSessionFactoryMagina(@Qualifier("masterDataSourceMagina") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        bean.setTypeAliasesPackage("com.magina.jta.mapper.one");
        return bean.getObject();
    }

    //注意定义的方法或者Bean的名字不要和jar包里面重复,不然setting spring.main.allow-bean-definition-overriding=true
    @Bean
    @Primary
    public SqlSessionTemplate jtaMasterSqlSessionTemplateMagina(
            @Qualifier("jtaMasterSqlSessionFactoryMagina") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}